package com.fanrui.code.player;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import com.fanrui.proto.cmd.PlayerInfoCmd;
import com.fanrui.proto.cmd.PlayerSimpleInfoCmd;

public class PlayerManager {
	
	// singleton
	private PlayerManager() {}
	
	private static class PlayerManagerSingleton {
		private static PlayerManager instance = new PlayerManager();
	}
	
	public static PlayerManager getInstance() {
		return PlayerManagerSingleton.instance;
	}

	/**
	 * 查找或者创建一个玩家(此处的创建是指在内存中创建一个用户)
	 * @param playerId
	 * @return
	 */
	public Player findOrCreatePlayer(Long playerId) {
		if(playerId == null){
			return null;
		}
		Player player = PlayerDao.getInstance().findById(playerId);
		if(player == null){// 内存中为找到改玩家
			player = PlayerDao.getInstance().createPlayerAndLoad(playerId);
		}
		return player;
	}
	/**
	 * 将Player转换成命令
	 */
	public  Collection<PlayerInfoCmd> playerToCmd(Collection<Player> players) {
		if(players != null && !players.isEmpty()){
			ArrayList<PlayerInfoCmd> result = new ArrayList<PlayerInfoCmd>();
			for(Player player:players){
				result.add(player.toCmd());
			}
			return result;
		}else{
			return Collections.emptyList();
		}
		
	}

	/**
	 * 将Player转换成命令
	 */
	public  PlayerSimpleInfoCmd playerToSimpleInfoCmd(Player player) {
		PlayerSimpleInfoCmd.Builder builder = PlayerSimpleInfoCmd.newBuilder();
		builder.setGold(player.getGold());
		builder.setId(player.getId());
		builder.setMoney(player.getMoney());
		builder.setNickName(player.getNickname());
		builder.setHeadIconUrl(player.getHeadUrl());
		builder.setTime(System.currentTimeMillis()/1000);
		return builder.build();
	}
	/**
	 * 将Player转换成命令
	 */
	public  Collection<PlayerSimpleInfoCmd> playerToSimpleInfoCmd(Collection<Player> players) {
		if(players != null && !players.isEmpty()){
			ArrayList<PlayerSimpleInfoCmd> result = new ArrayList<PlayerSimpleInfoCmd>();
			for(Player player:players){
				result.add(playerToSimpleInfoCmd(player));
			}
			return result;
		}else{
			return Collections.emptyList();
		}
	}
}
